﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.ClientApp.ViewModel;
using Galaktika.BI.Extensibility.Dom;
using Ranet.AgOlap.Controls.General;
using Ranet.AgOlap.Controls.ToolBar;
using Galaktika.BI.Silverlight.ClientApp.Items;
using Galaktika.BI.Silverlight.Controls;
using System.Windows.Media.Imaging;
using Galaktika.BI.Silverlight.Services;

namespace Galaktika.BI.Silverlight.ClientApp.View
{
    public partial class DefaultSettingOverrideForm : PopUpContainerControl
    {
        private const string IMAGE_SOURCE = "/Galaktika.BI.Silverlight.ClientApp;component/";
        private class VariablesTreeData
        {
            public VariablesTreeData(string name)
            {
                this.Name = name;
            }

            public readonly string Name;
            public readonly Dictionary<string, VariablesTreeData> Childen = new Dictionary<string, VariablesTreeData>();
            public DefaultSettingOverride.VariableSettingOverride Variable;
        }

        public DefaultSettingOverrideForm()
        {
            InitializeComponent();

            this.PopupControl.Caption = Localization.Str_Settings;
        }

        public event EventHandler Closed;
        protected virtual void OnClosed()
        {

            this.IsDropDownOpen = false;
            if (this.Closed != null)
            {
                this.Closed(this, EventArgs.Empty);
            }
        }

        public bool? DialogResult { get; set; }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.OnClosed();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.OnClosed();
        }

        private void EnsurePrivatesInitialized()
        {
            if (treeVariables != null) return;
            if (this.ContentControl == null) return;

            FrameworkElement fw = (FrameworkElement)this.ContentControl;
            treeVariables = fw.FindName("treeVariables") as TreeView;
            lblName = fw.FindName("lblName") as TextBlock;
            lblName.Text = Localization.Caption_Name;
            lblDefaultValue = fw.FindName("lblDefaultValue") as TextBlock;
            lblDefaultValue.Text = Localization.Caption_DefaultValue;
            lblTimeout = fw.FindName("lblTimeout") as TextBlock;
            lblTimeout.Text = Localization.Caption_TimeOut;
            //lblCurValue = fw.FindName("lblCurValue") as TextBlock;
            //lblCurValue.Text = Localization.Caption_CurrentValue;
            gridDetails = fw.FindName("gridDetails") as Grid;
            txtDefaultValue = fw.FindName("txtDefaultValue") as TextBox;

            tabSettings = fw.FindName("tabSettings") as TabPage;
            tabVariables = fw.FindName("tabVariables") as TabPage;

            tabSettings.Header = Localization.Caption_Common;
            tabVariables.Header = Localization.Caption_Variables;

            //tabSettings.Style = tabVariables.Style =
                //App.Current.Resources["TabControlMainItem"] as Style;

            tabMain = fw.FindName("tabMain") as TabPageContainer;
            //tabMain.Style = App.Current.Resources["TabControlOutput"] as Style;

            lblBaseUri = fw.FindName("lblBaseUri") as TextBlock;
            lblBaseUri.Text = Localization.Caption_BaseUri;

            lblCultureName = fw.FindName("lblCultureName") as TextBlock;
            lblCultureName.Text = Localization.Caption_Language;

            cboxCultureName = fw.FindName("cboxCultureName") as Selector;
            cboxCultureName.ItemsSource = new string[] {"en", "ru" };
            //cboxCultureName.SelectedItem = "en";

            cboxDataAccess = fw.FindName("cboxDataAccess") as Selector;
            cboxDataAccess.ItemsSource = new [] { DataAccessMode.Deffered, DataAccessMode.Immediate };
                //from f in typeof(DataAccessMode).GetFields()
                //where !f.IsSpecialName
                //select f.Name;

            gridSettings = fw.FindName("gridSettings") as Grid;

            lblDataAccess = fw.FindName("lblDataAccess") as TextBlock;
            lblDataAccess.Text = Localization.Caption_DataAccessMode;

            chkCache = fw.FindName("chkCache") as CheckBox;
            chkCache.Content = Localization.Caption_ClientCaching;

            chkLogging = fw.FindName("chkLogging") as CheckBox;
            chkLogging.Content = Localization.Caption_Logging;

            chkLogMdxQueries = fw.FindName("chkLogMdxQueries") as CheckBox;
            chkLogMdxQueries.Content = Localization.Caption_LogMdxQueries;

            OKButton = fw.FindName("OKButton") as SimpleButton;
            OKButton.Content = Localization.Str_Ok;
            CancelButton = fw.FindName("CancelButton") as SimpleButton;
            CancelButton.Content = Localization.Str_Cancel;

            tbMain = fw.FindName("tbMain") as RanetToolBar;
            var refreshBtn = new RanetToolBarButton() { Content = new Image() { Source = new BitmapImage(new Uri(IMAGE_SOURCE + "Items/Images/Refresh.png", UriKind.Relative)) } };
            ToolTipService.SetToolTip(refreshBtn, new StyledToolTip() { Content = Localization.Str_Refresh });
            refreshBtn.Click += new RoutedEventHandler(refreshBtn_Click);
            refreshBtn.Width = refreshBtn.Height = 16.0;
            tbMain.AddItem(refreshBtn);

            lblDescription = fw.FindName("lblDescription") as TextBlock;
            lblDescription.Text = Localization.Caption_Description;
        }

        void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            var settings = ClientAppHolder.GetUserSettins();
            this.LoadData(settings);
        }

        UserSettings m_Settings;
        DefaultSettingOverride m_ViewModel;
        public void LoadData(UserSettings settings)
        {
            m_Settings = settings;
            this.EnsurePrivatesInitialized();
            VariablesTreeData treeDesc = null;
            m_ViewModel = new DefaultSettingOverride(settings.Variables);

            foreach (var v in m_ViewModel.Variables)
            {
                string[] names = v.Name.Split('.');
                this.FillTreeData(v, names, 0, ref treeDesc);
            }

            treeVariables.Items.Clear();
            if (treeDesc != null)
            {
                this.CreateTreeNodes(treeVariables.Items, treeDesc);
            }

            gridSettings.DataContext = settings.Settings;
        }

        public UserSettings GetChangeSet()
        {
            var res = new UserSettings();
            res.Settings = m_Settings.Settings.Clone();
            foreach (var v in m_ViewModel.Variables)
            {
                if (v.IsChanged)
                {
                    v.CommitEdit();
                    v.Variable.CurrentValue = v.Variable.DefaultValue;
                    res.Variables.Add(v.Variable);
                }
            }

            return res;
        }

        private void FillTreeData(DefaultSettingOverride.VariableSettingOverride var, 
            string[] names, 
            int index, 
            ref VariablesTreeData data)
        {
            if (data == null)
            {
                data = new VariablesTreeData(names[index]);
            }

            index++;
            if (index < names.Length)
            {
                VariablesTreeData child;
                data.Childen.TryGetValue(names[index], out child);
                if (child == null)
                {
                    FillTreeData(var, names, index, ref child);
                    data.Childen.Add(names[index], child);
                }
                else
                {
                    FillTreeData(var, names, index, ref child);
                }
            }
            else
            {
                data.Variable = var;
            }
        }

        private void CreateTreeNodes(ItemCollection owner, VariablesTreeData data)
        {
            var item = new TreeViewItem();
            item.Header = data.Name;
            item.Style = App.Current.Resources["TreeViewItemGlowStyle"] as Style;
            item.Tag = data.Variable;
            owner.Add(item);

            foreach (VariablesTreeData child in data.Childen.Values)
            {
                this.CreateTreeNodes(item.Items, child);
            }
        }

        bool m_LockItemChanged = false;
        private void treeVariables_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (m_LockItemChanged) return;
            TreeViewItem treeViewItem = treeVariables.SelectedItem as TreeViewItem;
            if (treeViewItem != null && treeViewItem.Tag != null)
            {
                try
                {
                    m_LockItemChanged = true;
                    gridDetails.DataContext = treeViewItem.Tag;
                    txtDefaultValue.Focus();
                }
                finally
                {
                    m_LockItemChanged = false;
                }
            }
        }

        private void detailForm_CurrentItemChanged(object sender, EventArgs e)
        {
            if (m_LockItemChanged) return;
            //var v = detailForm.CurrentItem as DefaultSettingOverride.VariableSettingOverride;
            //if (v != null)
            {
                try
                {
                    m_LockItemChanged = true;
                    
                }
                finally
                {
                    m_LockItemChanged = false;
                }
            }
        }
    }
}

